package com.tianji.aigc.tools;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import com.tianji.aigc.config.ToolResultHolder;
import com.tianji.aigc.constants.Constant;
import com.tianji.aigc.tools.result.PrePlaceOrder;
import com.tianji.api.client.trade.TradeClient;
import com.tianji.api.dto.trade.OrderConfirmVO;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zgp
 * @version V1.0
 * @date 2025-04-23 12:12
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderTools {
    private final TradeClient tradeClient;

    @Tool(description = Constant.Tools.PRE_PLACE_ORDER_BY_COURSE_IDS)
    public PrePlaceOrder prePlaceOrder(@ToolParam(description = Constant.ToolParams.COURSE_IDS) List<Number> courseIds, ToolContext toolContext){
        List<Long> ids = courseIds.stream().map(Number::longValue).toList();
        // 1. 设置用户id，避免OpenFeign远程调用下单服务，无法拿到用户id而报错
        UserContext.setUser(Convert.toLong(toolContext.getContext().get(Constant.USER_ID)));
        // 2. 调用交易服务，进行预下单，获取订单确认页信息
        OrderConfirmVO orderConfirmVO = tradeClient.prePlaceOrder(ids);
        if(ObjUtil.isNull(orderConfirmVO)){
            return null;
        }
        PrePlaceOrder prePlaceOrder = PrePlaceOrder.of(orderConfirmVO);
        // 3. 将tool结果存入全局容器map中，用于流式对话返回前端
        String requestId = Convert.toStr(toolContext.getContext().get(Constant.REQUEST_ID));
        String field = "prePlaceOrder";
        ToolResultHolder.put(requestId, field, prePlaceOrder);
        return prePlaceOrder;
    }
}
